package demo.mq.rabbit;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import demo.java.net.HttpDemo;
import demo.java.util.Base64Demo;
import demo.vo.http.ResponseVo;

/**
 * Rabbit MQ 管理平台API
 * 
 * @author junying.han
 *
 */
public class RabbitMqManagement {

    private static Logger logger = LoggerFactory.getLogger(RabbitMqManagement.class);

    private String url;
    private String user;
    private String pass;

    /** 请求接口加密 */
    private Map<String, String> authorization;

    public RabbitMqManagement(String url, String user, String pass) {
        super();
        this.url = url;
        this.user = user;
        this.pass = pass;
        this.authorization = new HashMap<String, String>();
        authorization.put("authorization",
                "Basic " + Base64Demo.encode(String.format("%s:%s", user, pass).getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * <p>
     * http://192.168.3.161:15672/api/queues/%2F/207464ad-38ff-42ad-ae84-ddf13b69bac5/bindings
     * 
     * @throws IOException
     */
    public JSONArray queueBindings(String queueName) throws IOException {
        String path = url + "/api/queues/%2F/" + queueName + "/bindings";
        ResponseVo response = HttpDemo.httpRequest(path, null, RequestMethod.GET, authorization, 6000, 60_000);
        if (!response.getHttpStatus().is2xxSuccessful()) {
            logger.error("http requet failed, return :{}", response);
        }
        String data = response.getContent();
        return JSONObject.parseArray(data);
    }

    /**
     * 查找当前队列信息
     * <p>
     * http://192.168.3.161:15672/api/queues/%2F/207464ad-38ff-42ad-ae84-ddf13b69bac5?lengths_age=60&lengths_incr=5&msg_rates_age=60&msg_rates_incr=5
     * 
     * @param queueName
     * @param lengthsAge   时长（秒）
     * @param lengthsIncr  统计间隔（秒）
     * @param msgRatesAge  消息速率时长（秒）
     * @param msgRatesIncr 消息速率统计间隔（秒）
     * @return
     * @throws IOException
     */
    public JSONObject queuesBy(String queueName, Integer lengthsAge, Integer lengthsIncr, Integer msgRatesAge,
            Integer msgRatesIncr) throws IOException {
        String path = url + "/api/queues/%2F/" + queueName;
        Map<String, Integer> params = new LinkedHashMap<String, Integer>();
        if (lengthsAge != null) {
            params.put("lengths_age", lengthsAge);
        }
        if (lengthsIncr != null) {
            params.put("lengths_incr", lengthsIncr);
        }
        if (msgRatesAge != null) {
            params.put("msg_rates_age", msgRatesAge);
        }
        if (msgRatesIncr != null) {
            params.put("msg_rates_incr", msgRatesIncr);
        }
        if (!params.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (Entry<String, Integer> entry : params.entrySet()) {
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            path += sb.replace(0, 1, "?");
        }
        logger.info(path);
        ResponseVo response = HttpDemo.httpRequest(path, null, RequestMethod.GET, authorization, 6000, 60_000);
        if (!response.getHttpStatus().is2xxSuccessful()) {
            logger.error("http requet failed, return :{}", response);
        }
        String data = response.getContent();
        return JSONObject.parseObject(data);
    }

    /**
     * 
     * <p>
     * http://192.168.3.161:15672/api/vhosts
     * 
     * @throws IOException
     */
    public ResponseVo vhosts() throws IOException {
        String path = url + "/api/vhosts";
        return HttpDemo.httpRequest(path, null, RequestMethod.GET, authorization, 6000, 60_000);
    }

    /**
     * 查找所有队列消费情况
     * <p>
     * http://192.168.3.161:15672/api/queues
     * 
     * @throws IOException
     */
    public JSONArray queues() throws IOException {
        String path = url + "/api/queues";
        ResponseVo response = HttpDemo.httpRequest(path, null, RequestMethod.GET, authorization, 6000, 60_000);
        if (!response.getHttpStatus().is2xxSuccessful()) {
            logger.error("http requet failed, return :{}", response);
        }
        String data = response.getContent();
        return JSONObject.parseArray(data);
    }

    public String getUrl() {
        return url;
    }

    public String getUser() {
        return user;
    }

    public String getPass() {
        return pass;
    }

}
